package com.xn.myyxcampus.fragment;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.xn.myyxcampus.LoadingActivity;
import com.xn.myyxcampus.R;
import com.xn.myyxcampus.http.URLs;
import com.xn.myyxcampus.utils.AnimUtils;
import com.xn.myyxcampus.utils.MD5;
import com.xn.myyxcampus.utils.MyPreferences;
import com.xn.myyxcampus.utils.ToastUtils;

public class LoginFragment extends BaseFragment implements OnClickListener {

	private ImageView showMenu;
	private EditText userName;
	private EditText userPass;
	private Button login;
	private ImageView loading;
	/** 登录成功，先把头像文件夹下的图片删掉，下载登陆的用户头像 */
	private static final String Left_head_DIR = Environment
			.getExternalStorageDirectory() + "/DCIM/Tracy/HeadPhoto/";
	private HttpUtils httpUtil = new HttpUtils();

	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.login, null);
		File file = new File(Left_head_DIR);
		file.mkdir();
		showMenu = (ImageView) view.findViewById(R.id.ivlogin_showMenu);
		userName = (EditText) view.findViewById(R.id.et_userName);
		userPass = (EditText) view.findViewById(R.id.et_userPass);
		login = (Button) view.findViewById(R.id.b_login);
		loading = (ImageView) view.findViewById(R.id.iv_loginLoading);

		showMenu.setOnClickListener(this);
		login.setOnClickListener(this);
		return view;
	}

	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ivlogin_showMenu:
			showLeft();
			break;
		case R.id.b_login:
			animationDrawable = (AnimationDrawable) loading.getBackground();
			animationDrawable.start();
			loading.setVisibility(View.VISIBLE);
			final String uName = userName.getText().toString().trim();
			final String uPass = MD5.md5(userPass.getText().toString().trim());
			RequestParams params = new RequestParams();
			params.addBodyParameter("name", uName);
			params.addBodyParameter("pwd", uPass);
			httpUtil.send(HttpRequest.HttpMethod.POST, URLs.USER_LOGIN, params,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							// TODO Auto-generated method stub
							ToastUtils.showToast("网络异常");
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							// TODO Auto-generated method stub
							LogUtils.i(arg0.result);
							ObjectMapper mapper = new ObjectMapper();
							try {
								HashMap<String, Object> map = mapper.readValue(
										arg0.result, HashMap.class);
								int response = (Integer) map.get("response");
								LogUtils.i("response" + response);
								if (1 == response) {
									String headpic = (String) map
											.get("headpic");
									String name = (String) map.get("name");
									String uid = (String) map.get("uid");
									
									SharedPreferences sp = MyPreferences.getShare();
									Editor edit = sp.edit();
									edit.putString("name", name);
									edit.putString("pass", uPass);
									edit.putString(MyPreferences.TOKEN, uid);
									edit.commit();
									
									if (!TextUtils.isEmpty(headpic)) {
										String imgUrl = URLs.HEDD_PHOTO
												+ headpic.replace('+', '/');
										downloadImg(imgUrl, headpic);
									}
								} else {
									String tips = (String) map.get("tips");
									ToastUtils.showToast(tips);
								}

							} catch (JsonParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonMappingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
			break;
		}
	}

	private void downloadImg(String imgUrl, String headPic) {
		httpUtil.download(imgUrl, Left_head_DIR + headPic,
				new RequestCallBack<File>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								LoadingActivity.class);
						LogUtils.i("imgUrl:" + Left_head_DIR);
						intent.putExtra("loadTime", 500);
						animationDrawable.stop();
						loading.setVisibility(View.GONE);
						startActivity(intent);
						AnimUtils.scaleIn(getActivity());
						getActivity().finish();
					}
				});
	}

}
